package com.m3839.sdk.ym.ext

import android.annotation.TargetApi
import android.content.Context
import android.content.res.Configuration
import android.graphics.Point
import android.os.Build
import android.view.Display
import android.view.WindowManager

/**
 * @description: ScreenExt
 *
 * @author ChenBaoyang
 * @date 6/15/21 13:46
 */

/**
 * 描述：dip转换px
 *
 * @receiver Context
 * @param dipValue
 * @return Int
 */
fun Context.dip2px(dipValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (dipValue * scale + 0.5f).toInt()
}

/**
 * 描述：px转换dip
 *
 * @receiver Context
 * @param pxValue
 * @return Int
 */
fun Context.px2dip(pxValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}

/**
 * 从sp到px
 *
 * @receiver Context
 * @param spValue
 * @return Int
 */
fun Context.sp2px(spValue: Float): Int {
    val fontScale = resources.displayMetrics.scaledDensity
    return (spValue * fontScale + 0.5f).toInt()
}

/**
 * px 2 sp
 *
 * @receiver Context
 * @param pxValue
 * @return Int
 */
fun Context.px2sp(pxValue: Float): Int {
    val fontScale = resources.displayMetrics.scaledDensity
    return (pxValue / fontScale + 0.5f).toInt()
}

/**
 * 获取物理屏幕高度
 * @receiver Context
 * @return Int
 */
val Context.getScreenHeight: Int
    get() {
        var screenHeight = 0
        screenHeight = if (Build.VERSION.SDK_INT >= 13) {
            val display = getDefaultDisplay(this)
            val size = Point()
            display.getSize(size)
            size.y
        } else {
            val dm = resources.displayMetrics
            dm.heightPixels
        }
        return screenHeight
    }

/**
 * 获取物理屏幕宽度
 * @receiver Context
 * @return Int
 */
val Context.getScreenWidth: Int
    get() {
        var screenWidth = 0
        screenWidth = if (Build.VERSION.SDK_INT >= 13) {
            val display = getDefaultDisplay(this)
            val size = Point()
            display.getSize(size)
            size.x
        } else {
            val dm = resources.displayMetrics
            dm.widthPixels
        }
        return screenWidth
    }



private fun getDefaultDisplay(context: Context): Display {
    val wm =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    return wm.defaultDisplay
}


/**
 * 返回当前屏幕是否为竖屏。
 * @receiver Context
 * @return Boolean 当且仅当当前屏幕为竖屏时返回true,否则返回false。
 */
fun Context.isScreenOrientationPortrait(): Boolean {
    return resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
}